<template>
  <div class="min-h-screen bg-gray-100 flex flex-col items-center justify-center p-6">
    <div class="bg-white shadow-lg rounded-2xl p-6 w-full max-w-md">
      <h1 class="text-2xl font-bold text-center mb-4">Go OCR 服务</h1>

      <form @submit.prevent="handleUpload" class="flex flex-col gap-4">
        <input type="file" accept="image/*" @change="onFileChange" class="border p-2 rounded" />
        <button
            type="submit"
            class="bg-blue-500 hover:bg-blue-600 text-white py-2 rounded"
            :disabled="loading"
        >
          {{ loading ? "识别中..." : "上传并识别" }}
        </button>
      </form>

      <div v-if="result" class="mt-4 bg-gray-50 border p-3 rounded whitespace-pre-wrap">
        <strong>识别结果：</strong>
        <p>{{ result }}</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from "vue";
import axios from "axios";

const file = ref(null);
const result = ref("");
const loading = ref(false);

function onFileChange(e) {
  file.value = e.target.files[0];
}

async function handleUpload() {
  if (!file.value) return;
  loading.value = true;
  const formData = new FormData();
  formData.append("image", file.value);
  try {
    const res = await axios.post("/ocr", formData);
    result.value = res.data.text;
  } catch (err) {
    result.value = "错误：" + err.message;
  } finally {
    loading.value = false;
  }
}
</script>
